// pages/child_info/child_info.js
import { getData } from "../mine/function";

const db = wx.cloud.database();
const _ = db.command;

var wxCharts = require("../../utils/wxcharts.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    donorInfo: '',
    showIndex: null,
    child: {
      id: '',
      name: '',
      province: '',
      tag: '',
      imgUrl: '',
      money: 0,
    },

    donateMoney: 0,
    moneys: [20, 50, 100, 200],
    donateType: "",
    types: ['每月支付', '一次支付'],
    selectedIndex_toDonoteChild: -1,
    selectedIndex_payway: -1,

    showDialog: false,


  },

  // 原生
  onMoneyButtonTap(event) {
    const { index, selected } = event.currentTarget.dataset;
    //console.log(index,selected);
    if (selected) {
      return; // 如果按钮已经选中，则不执行任何操作
    }
    this.setData({
      selectedIndex_toDonoteChild: index
    });
  },
  onPaymentButtonTap(event) {
    const { index } = event.currentTarget.dataset;
    // console.log(index);
    this.setData({
      selectedIndex_payway: index
    });
  },

  // 捐款
  async confirmPay(event) {
    // console.log("确认支付")
    this.data.donateMoney = this.data.moneys[this.data.selectedIndex_toDonoteChild]
    this.data.donateType = this.data.types[this.data.selectedIndex_payway]

    const tmpChild = await db.collection('childInfo').where({
      studentName: this.data.child.name,
    }).get()

    const theChild = tmpChild.data[0]

    db.collection('childInfo').where({
      studentName: theChild.studentName
    }).update({
      data: {
        times: theChild.times + 1
      }
    }).then(res => {
      // console.log("timesLog")
      // console.log(res)
    })

    const donorInfo = this.data.donorInfo;

    var totalDonation = donorInfo.totalDonation || {}; // 如果字段不存在则创建一个空对象
    totalDonation['nov'] = (totalDonation['nov'] || 0) + this.data.donateMoney;

    var donorStudentsRes = await db.collection('donor').doc(donorInfo._id).get();
    var donorStudents = donorStudentsRes.data.students;

    // console.log("donorStudents");
    // console.log(donorStudents);

    const selectedStudentIndex = donorStudents.findIndex(student => student.name === theChild.studentName);
    if (selectedStudentIndex === -1) {
      console.log("尚未捐助过该学生");

      var newChild = {
        date: this.getLocalDate(),
        imgUrl: theChild.imgUrl,
        name: theChild.studentName,
        province: theChild.province,
        tag: theChild.tag,
        money: this.data.donateMoney,
        times: 1,
      }


      donorStudents.push(newChild);
      db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      // 更新捐款后的钱数
      var tmpChildMoney = this.data.child;
      tmpChildMoney.money = parseFloat(tmpChildMoney.money) + this.data.donateMoney;
      this.setData({
        showDialog: true,
        child: tmpChildMoney,
      })

    } else {
      console.log("拿到了捐助过的这名学生的信息");
      // console.log(donorStudents[selectedStudentIndex])
      donorStudents[selectedStudentIndex].times += 1;
      donorStudents[selectedStudentIndex].money += this.data.donateMoney;

      const updateDonorRes = await db.collection('donor').doc("f18e14fa6543438604a4c12e76abaa0f").update({
        data: {
          times: _.inc(1),
          credit: _.inc(this.data.donateMoney * 0.2),
          students: donorStudents,
          totalDonation: totalDonation
        }
      });

      // console.log(updateDonorRes);

      // 更新捐款后的钱数
      var tmpChildMoney = this.data.child;
      tmpChildMoney.money = parseFloat(tmpChildMoney.money) + this.data.donateMoney;
      this.setData({
        showDialog: true,
        child: tmpChildMoney,
      })


    }


  },

  // util
  getLocalDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const formattedDate = `${year}.${month.toString().padStart(2, '0')}.${date.toString().padStart(2, '0')}`;
    return formattedDate;
    // const now = new Date();
    // return now.toLocaleDateString('zh-CN');
  },
  async init() {
    var res = await getData("ourOx68K-yzP1JGUbwnM9FAEJ8hA");
    // console.log(res);
    this.setData({
      donorInfo: res,
      donatedChildren: res.students,
    })
    // console.log("donorInfo")
    // console.log(this.data.donorInfo)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init()
    // console.log(options.money + "ww")
    this.setData({
      child: {
        id: options.id,
        name: options.name,
        province: options.location,
        tag: options.tag,
        imgUrl: options.imgUrl,
        money: options.money,
        selectedIndex_else: 0,
        selectedIndex_toDonoteChild: -1,
        selectedIndex_payway: -1,
      }
    })
    // console.log(this.data.money);
  },

  onClickContribution() {
    // console.log('点击');
  },

  onShow() {
    this.init()
    let windowHeight = 900;
    let windowWidth = 320;
    try {
      let res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
      windowHeight = res.windowHeight;
    } catch (e) {
    }
    let chartCategories = ['9月', '10月', '11月', '12月']
    let chartData1 = [93, 85, 86, 88]
    let chartData2 = [80, 75, 85, 80]
    new wxCharts({
      canvasId: 'areaCanvas',
      type: 'area',
      categories: chartCategories,
      series: [{
        name: '所得积分',
        data: chartData1,

      }, {
        name: '平均积分',
        data: chartData2,
        format: function (val) {
          return "";
        },
      }],
      yAxis: {
        title: '积分 (分)',
        format: function (val) {
          return val;
        },
        min: 0,
        max: 100
      },
      width: 0.9 * windowWidth,
      height: 0.36 * windowHeight
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  openPopup(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showIndex: index
    })
    // console.log(this.data.showIndex);
  },
  closePopup() {
    this.setData({
      showIndex: null
    })
  }
})